package com.hxh.tess4j.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;

/**
 * @author huangxunhui
 * Date: Created in 2019-04-15 23:18
 * Utils: Intellij Idea
 * Description:
 */
@Slf4j
public class OkhttpUtil {

    public static String get(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuilder sb = new StringBuilder(url);
        addParams(queries, sb);
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("e");
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    public static String postJsonParams(String url, String jsonParams) {
        String responseBody = "";
        okhttp3.RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("e");
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }



    private static void addParams(Map<String, String> queries, StringBuilder sb) {
        if (queries != null && !queries.keySet().isEmpty()) {
            boolean firstFlag = (!sb.toString().contains("?"));
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
    }

    public static String getNum(){
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(9));
        }
        return stringBuilder.toString();
    }

}
